﻿
using Singer.BackgroundJob.RabbitMQ.Contracts;
using Singer.UnitTestWeb.BackgroundJobs.JobArgs;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Singer.Shared.UserContext;
using Singer.BackgroundJob.RabbitMQ;
using Singer.BackgroundJob.RabbitMQ.BackgroundJobLogs;

namespace Singer.UintTestBackgroundJob.JobExecutors;

[BackgroundJobExecutor(typeof(AuthorJobArgs), "Author测试任务", IsSystemJob = true)]
public class AuthorJobExecutor : BackgroundJobExecutorBase<AuthorJobArgs>
{
    private readonly ILogger<AuthorJobExecutor> _logger;
    private readonly IUserContextAccessor _userContextAccessor;

    public AuthorJobExecutor(
        ILogger<AuthorJobExecutor> logger,
        BackgroundJobLogManager backgroundJobLogManager,
        IUserContextAccessor userContextAccessor) : base(backgroundJobLogManager)
    {
        _logger = logger;
        _userContextAccessor = userContextAccessor;
    }

    public override async Task ExecuteAsync()
    {
        _logger.LogInformation($"【{nameof(AuthorJobExecutor)}】触发，" +
            $"【JobArgs】：'{JsonConvert.SerializeObject(JobLog.Args)}'；" +
            $"【UserContext】：'{JsonConvert.SerializeObject(_userContextAccessor.UserContext)}'。");
        for (int i = 1; i <= 30; i++)
        {
            if (StoppingCts.IsCancellationRequested) // 任务取消时，跳出循环
                break;
            Console.WriteLine($"任务执行中...{i}");
            await LogInfoAsync($"任务执行中...{i}");
            await Task.Delay(1000);
        }
        _logger.LogInformation($"【{nameof(AuthorJobExecutor)}】任务执行完成。");
    }


    public override async Task CancelledAsync()
    {
        await base.CancelledAsync();
        _logger.LogInformation($"【{nameof(AuthorJobExecutor)}】任务取消...");
    }
}
